package org.snail.quartz;

import lombok.extern.log4j.Log4j;
import org.quartz.*;
import org.quartz.impl.StdSchedulerFactory;
import org.springframework.stereotype.Component;

//TODO 需要将定时器制作成底层，通用工具类，并且需要知道正在运行的定时器的具体信息，就是需要进行详细的配置
@Component
@Log4j
public class QuartzSchedulingUtils {

    private static SchedulerFactory schedulerFactory = new StdSchedulerFactory();

    /**
     * 创建定时器任务
     *
     * @param jobName  任务名称
     * @param jobGroupName  任务群组名称
     * @param triggerName  触发器名称
     * @param triggerGroupName 触发器组名
     * @param jobClass 任务
     * @param cron 时间设置
     */
    @SuppressWarnings({ "unchecked", "rawtypes" })
    public static void addJob(String jobName, String jobGroupName,
                              String triggerName, String triggerGroupName, Class jobClass, String cron) {
        try {
            Scheduler sched = schedulerFactory.getScheduler();
            // 任务名，任务组，任务执行类
            JobDetail jobDetail= JobBuilder.newJob(jobClass).withIdentity(jobName, jobGroupName).build();

            // 触发器
            TriggerBuilder<Trigger> triggerBuilder = TriggerBuilder.newTrigger();
            // 触发器名,触发器组
            triggerBuilder.withIdentity(triggerName, triggerGroupName);
            triggerBuilder.startNow();
            // 触发器时间设定
            triggerBuilder.withSchedule(CronScheduleBuilder.cronSchedule(cron));
            // 创建Trigger对象
            CronTrigger trigger = (CronTrigger) triggerBuilder.build();

            // 调度容器设置JobDetail和Trigger
            sched.scheduleJob(jobDetail, trigger);

            // 启动
            if (!sched.isShutdown()) {
                sched.start();
            }
            log.error("========================定时器启动成功！time =" + cron);
        } catch (Exception e) {
            log.error("定时器启动失败！", e);
            throw new RuntimeException(e);
        }
    }

}
